var fs = require('fs');
	var request = require("request");
	var cheerio = require("cheerio");
	var mkdirp = require('mkdirp');

	//目标网址
	// var url = 'http://92.t9p.today/viewthread.php?tid=243625&extra=page%3D2';
	 var url = 'http://92.t9p.today/forumdisplay.php?fid=19&page=2'
// templates/fervor/images/logo.gif'
	//本地存储目录
	var dir = './imagess';
	 
	//创建目录
	mkdirp(dir, function(err) {
		if(err){
			console.log(err);
		}
	});
	 
	//发送请求
	request(url, function(error, response, body) {
		if(!error && response.statusCode == 200) {
			console.log('111')
			   response.setEncoding("binary")
				var $ = cheerio.load(body);
			$('a').each(function(i,e){
				var href = $(this).attr('href');
				console.log('开始链接')
				if(href.substr(0,4)=='view'&&href.substr(-4,4)=='%3D2'){
						let ll = 'http://92.t9p.today/' + href;
					console.log(ll,i)
					request(ll,function(err,res,body){
						if(!error && response.statusCode == 200) {
							console.log('链接成功')
							let $ = cheerio.load(body);
							console.log($('html').find('img').length)
							$('html').find('img').each(function(){
								console.log('开始下载')
							if($(this).attr('file')){
								console.log('找到目标')
					var src ='http://92.t9p.today/' + $(this).attr('file');
					console.log(src)
						download(src, dir, Math.floor(Math.random()*100000) + src.substr(-4,4));
				}
				
							})
						}
					})
				}
			
			})
		}else{
			console.log('hahaha')
		}
	});
	 
	//下载方法
	var download = function(url, dir, filename){
		request.head(url, function(err, res, body){
			request(url).on('close',function(){console.log('done')}).on('error',function(err){console.log(err)}).pipe(fs.createWriteStream(dir + "/" + filename));
		});
	};